package com.lxm.sevice.sen;

import com.lxm.Interface.SendingInterFace;
import com.lxm.action.ActionBase;
import com.lxm.dao.MsgMapperDao;
import com.lxm.dao.WxMapperDao;
import com.lxm.entity.ReturnMessage;
import com.lxm.entity.SmsSenMsgEntity;
import com.lxm.entity.UserEntity;
import com.lxm.entity.query.QuerySenData;
import com.lxm.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author ：Administrator
 * @date :创建时间 2021/12/28 12:58
 */
@Service
public class PublicSenServiceImpl implements PublicSenService {
    public static HashMap<String, String> senBean = new HashMap<>();
    @Value("${urlPath.local_host_url}")
    private String queryUrl;
    @Autowired
    private MsgMapperDao msgMapperDao;

    static {
        senBean.put("0", "WxSendMsg");
        senBean.put("1", "QQSendMsg");
    }


    @Autowired
    private WxMapperDao wxMapperDao;

    @Override
    public ReturnMessage PublicSneMsg(String authCode, QuerySenData querySenData) {
        UserEntity quyer = new UserEntity();
        quyer.setAuthCode(authCode);
        UserEntity userEntity = wxMapperDao.queryUserData(quyer);
        if (Objects.isNull(userEntity)) {
            return ActionBase.error("没有找到用户,请关注公众号重试");
        }
        if (!"0".equals(userEntity.getUserState())) {
            return ActionBase.error("该用户状态异常,请联系管理员");
        }
        SmsSenMsgEntity smsSenMsgEntity = SmsSenMsgEntity.buildSmsSenMsgEntity(userEntity, querySenData);
        msgMapperDao.insertSenMsgAndGetId(smsSenMsgEntity);
        String url = queryUrl + "/showSenMsg?id=%s&authCode=%s";
        url = String.format(url, smsSenMsgEntity.getId(), quyer.getAuthCode());
        querySenData.setQueryUrl(url);
        senService bean = null;
        if (Objects.nonNull(querySenData.getSendLogo()) && Objects.nonNull(senBean.get(querySenData.getSendLogo()))) {
            bean = SpringUtil.getBean(senBean.get(querySenData.getSendLogo()), senService.class);
        } else {
            //默认查询微信的数据
            bean = SpringUtil.getBean(senBean.get("0"), senService.class);
        }
        ReturnMessage returnMessage = bean.sneMsg(userEntity, querySenData);
        if (returnMessage.IsSuccess()) {
            upDataUserSenNumber(userEntity);
        }
        return returnMessage;
    }


    public void upDataUserSenNumber(UserEntity user) {
        Integer currentSenNum = user.getCurrentSenNum();
        user.setCurrentSenNum(currentSenNum + 1);
        user.setOneDayNum(user.getOneDayNum() + 1);
        wxMapperDao.update(user);
    }
}
